package user_info

import (
	"encoding/json"
	"errors"
	"strconv"
	"strings"
	"sync"

	"gitlab.gaodun.com/golib/gderror"
	"permission/api/param_type"
	"permission/config/error_code"
	"permission/databases"
	"permission/vigo_loger"
	"permission/vigo_tool"
)

var p sync.Mutex

type sessStruct struct {
	userId int64
	appId  int32
}

func ERPLogin(erpguid string, appId int32, gdSid string) (param_type.ApiUserInfoResponse, error, error_code.Code_type_int) {
	var resData param_type.ApiUserInfoResponse
	data, err, status := VerifyERPAccount(erpguid)
	if err != nil || status != error_code.SUCCESS_STATUS {
		return resData, err, status
	}

	cache := NewVigoCache()
	defer cache.Close()
	userIdStr := strconv.FormatInt(data.UserID, 10)
	keyUserStr := userIdStr + VIGO_USER
	resData.Tpo_Sys_Users = data
	homePage := GetHomePage(data.UserID, appId)
	resData.HomePage = homePage
	// 设置缓存
	cache.SetVigoInfoCacheLog(keyUserStr, resData)
	expire := cache.GetExpire()
	cache.SetExpire(7 * 24 * 60 * 60) //  七天
	cache.SetVigoInfoCacheLog(gdSid, resData)
	cache.SetExpire(expire)

	return resData, nil, error_code.SUCCESS_STATUS
}

// 获取所有用户信息

//Login 登陆
func Login(account, password string, appId int32) (param_type.ApiUserInfoResponse, error, error_code.Code_type_int) {
	var resData param_type.ApiUserInfoResponse
	data, err, status := VerifyAccount(account, password)
	if err != nil {
		return resData, err, status
	}
	// 缓存读取数据
	cache := NewVigoCache()
	defer cache.Close()
	userIdStr := strconv.FormatInt(data.UserID, 10)
	keyUserStr := userIdStr + VIGO_USER
	resData.Tpo_Sys_Users = data
	homePage := GetHomePage(data.UserID, appId)
	resData.HomePage = homePage
	// 设置缓存
	cache.SetVigoInfoCacheLog(keyUserStr, resData)
	expire := cache.GetExpire()
	cache.SetExpire(7 * 24 * 60 * 60) //  七天
	cache.SetVigoInfoCacheLog("login_"+userIdStr, resData)
	cache.SetExpire(expire)

	return resData, nil, error_code.SUCCESS_STATUS
}

func ChangePwd(account, oldPassword, newPassword string) (error, error_code.Code_type_int) {
	data, err, status := VerifyAccount(account, oldPassword)
	if err != nil {
		return err, status
	}
	if ok := vigo_tool.VerifyPwd(newPassword); !ok {
		return errors.New("password format fail"), error_code.PASSWORD_FORMAT_ERR
	}
	password := vigo_tool.GetPassword(newPassword, "")
	userFac := databases.NewUserFactory()
	err = userFac.EditPwd(data.UserID, password[0:20])
	if err != nil {
		return err, error_code.PARAM_ERR
	}
	return nil, error_code.SUCCESS_STATUS
}

func VerifyERPAccount(erpguid string) (u databases.Tpo_Sys_Users, err error, code error_code.Code_type_int) {
	ds, err := GetUserInfoByErp(erpguid)
	if err != nil {
		return u, err, error_code.DB_ERR
	}

	if len(ds) == 0 {
		return u, err, error_code.PASSWORD_ERR
	}

	return ds[0], err, error_code.SUCCESS_STATUS
}

//VerifyAccount 验证用户帐密
func VerifyAccount(account, password string) (databases.Tpo_Sys_Users, error, error_code.Code_type_int) {
	var userData databases.Tpo_Sys_Users
	accType, err := vigo_tool.IsPhoneOrEmail(account)
	userFac := databases.NewUserFactory()
	if err != nil {
		return userData, err, error_code.PHONE_EMAIL_NOT_EXISTS_ERR
	}
	if accType == vigo_tool.EMAIL {
		userFac.GetUserInfoByEmail(account)
	} else if accType == vigo_tool.PHONE {
		userFac.GetUserInfoByPhone(account)
	}
	password = vigo_tool.GetPassword(password, "")
	passByte := []byte(password)
	if strings.ToUpper(string(passByte[0:20])) != strings.ToUpper(userFac.Table.Password) {
		return userData, errors.New("passwrod fail"), error_code.PASSWORD_ERR
	}
	return userFac.Table, nil, error_code.SUCCESS_STATUS
}

// 获取用户首页
func GetHomePage(userId int64, appId int32) string {
	homeFac := databases.NewHomePageFactory()
	homeFac.GetInfoByUidAndAppId(userId, appId)
	return homeFac.Table.HomePage
}

// 获取会话信息
func GetSession(userId int32, appId int32) (param_type.ApiSessionInfoResponse, error, error_code.Code_type_int) {
	var apiSessData param_type.ApiSessionInfoResponse
	cache := NewVigoCache()
	defer cache.Close()
	val := cache.CheckLogin(userId)
	if val == nil {
		return apiSessData, errors.New("login out"), error_code.LOGIN_OUT_ERR
	}
	json.Unmarshal(val.([]byte), &apiSessData.TpoSysUsers.Tpo_Sys_Users)
	res, err, status := GetSessionInfo(apiSessData.TpoSysUsers.Tpo_Sys_Users.UserID, appId)
	res.TpoSysUsers = apiSessData.TpoSysUsers
	res.TpoAliyunMQ, _ = FindUserAliMQ([]int64{apiSessData.TpoSysUsers.UserID})
	return res, err, status
}

// 刷新并缓存会话信息 @cache api
func GetSessionInfo(userId int64, appId int32) (param_type.ApiSessionInfoResponse, error, error_code.Code_type_int) {
	var apiSessData param_type.ApiSessionInfoResponse
	// 角色权限节点
	rolesDAta, err, status := GetRoles(userId)
	if err != nil {
		return apiSessData, err, status
	}

	// 功能
	funcData, err, status := GetFunc(appId, userId, rolesDAta.Data)
	if err != nil {
		return apiSessData, err, status
	}

	// 菜单
	naviData, err := GetNavigationTree(appId, userId)
	if err != nil {
		return apiSessData, err, status
	}

	// 菜单功能
	navFunData, err, status := GetNaviFuncListByFuncList(&funcData, appId, userId)
	if err != nil {
		return apiSessData, err, status
	}
	apiSessData.TpoSysNavigationFunction = navFunData

	apiSessData.TpoSysNavigations = naviData

	apiSessData.TpoSysRoles = rolesDAta.Data

	apiSessData.TpoSysFunctions = funcData

	return apiSessData, nil, error_code.SUCCESS_STATUS
}

//
func GetFunc(appId int32, userId int64, roles []databases.Tpo_Sys_Roles) ([]databases.Tpo_Sys_Functions, error, error_code.Code_type_int) {
	var data []databases.Tpo_Sys_Functions
	cache := NewVigoCache()
	defer cache.Close()
	userIdStr := strconv.FormatInt(userId, 10)
	funcKey := strconv.Itoa(int(appId)) + "_" + userIdStr + VIGO_FUNCTION
	res := cache.GetVigoInfoCache(funcKey)
	if res != nil {
		err := json.Unmarshal(res.([]byte), &data)
		if err == nil {
			return data, err, error_code.SUCCESS_STATUS
		}
	}
	funcData, err, status := GetUserFunc(appId, userId)
	if err != nil {
		return data, err, status
	}
	funcData2, err, status := GetFuncByRole(roles)
	if err != nil {
		return data, err, status
	}

	for _, val := range funcData2 {
		if val.AppId == int64(appId) {
			funcData = append(funcData, val)
		}
	}
	cache.SetVigoInfoCache(funcKey, funcData)

	return funcData, nil, error_code.SUCCESS_STATUS
}

func GetFuncByRole(roles []databases.Tpo_Sys_Roles) ([]databases.Tpo_Sys_Functions, error, error_code.Code_type_int) {
	var roleIds []int64
	for _, val := range roles {
		roleIds = append(roleIds, val.RoleId)
	}
	return GetFuncByRoleIds(roleIds)
}

// 获取角色的功能点
func GetFuncByRoleIds(RoleIds []int64) ([]databases.Tpo_Sys_Functions, error, error_code.Code_type_int) {
	var data []databases.Tpo_Sys_Functions
	rff := databases.NewFuncFactory()
	err := rff.FindFunctionByRoleIds(RoleIds...)
	if len(rff.RowsSlicePtr) == 0 {
		return rff.RowsSlicePtr, nil, error_code.SUCCESS_STATUS
	}
	if err != nil {
		return data, err, error_code.PARAM_ERR
	}
	return rff.RowsSlicePtr, nil, error_code.SUCCESS_STATUS
}

// 获取功能菜单列表 by 功能列表
func GetNaviFuncListByFuncList(data *[]databases.Tpo_Sys_Functions, appId int32, userId int64) ([]databases.Tpo_Sys_Navigation_Function, error, error_code.Code_type_int) {
	var datas []databases.Tpo_Sys_Navigation_Function
	cache := NewVigoCache()
	defer cache.Close()
	funcKey := strconv.Itoa(int(appId)) + "_" + strconv.Itoa(int(appId)) + VIGO_FUNC_NAV
	val := cache.GetVigoInfoCache(funcKey)
	if val != nil {
		json.Unmarshal(val.([]byte), &datas)
		return datas, nil, error_code.SUCCESS_STATUS
	}
	// 获取角色对应该功能 id
	roleIds, _, _ := GetRoleIds(userId)
	roleNavF := databases.NewRoleNavFuncFactory()
	roleNavF.FindByRoleIds(roleIds...)
	funcIds := []int64{}
	for _, val := range roleNavF.RowsSlicePtr {
		funcIds = append(funcIds, val.FunctionId)
	}
	// 缓存
	for _, val := range *data {
		funcIds = append(funcIds, val.FunctionId)
	}
	if len(funcIds) == 0 {
		return datas, nil, error_code.SUCCESS_STATUS
	}
	datas, err, status := GetNaviFuncList(funcIds...)
	cache.SetVigoInfoCache(funcKey, datas)
	return datas, err, status
}

// 获取功能菜单列表
func GetNaviFuncList(funcIds ...int64) ([]databases.Tpo_Sys_Navigation_Function, error, error_code.Code_type_int) {
	navFunFac := databases.NewNavigationFunFactory()
	err := navFunFac.FindInfoByFuncIds(funcIds...)
	if err != nil {
		return navFunFac.RowsSlicePtr, err, error_code.PARAM_ERR
	}
	return navFunFac.RowsSlicePtr, nil, error_code.SUCCESS_STATUS
}

// 获取用户的功能点
func GetUserFunc(appId int32, userId int64) ([]databases.Tpo_Sys_Functions, error, error_code.Code_type_int) {
	var data []databases.Tpo_Sys_Functions
	funcFac := databases.NewFuncFactory()
	funcFac.FindInfoByUserAndAppId(appId, userId)
	for _, val := range funcFac.UserFuncPtr {
		data = append(data, val.Tpo_Sys_Functions)
	}
	return data, nil, error_code.SUCCESS_STATUS
}

// 获取 app 功能点 @cache db
func GetFunctions(appId int32) ([]databases.Tpo_Sys_Functions, error, error_code.Code_type_int) {
	var data []databases.Tpo_Sys_Functions
	cache := NewVigoCache()
	defer cache.Close()
	funcKey := strconv.Itoa(int(appId)) + VIGO_FUNCTION
	val := cache.GetVigoInfoCache(funcKey)
	if val != nil {
		json.Unmarshal(val.([]byte), &data)
		return data, nil, error_code.SUCCESS_STATUS
	}
	// 读数据 写缓存
	funcFac := databases.NewFuncFactory()
	err := funcFac.FindInfoByAppId(appId)
	if err != nil {
		return funcFac.RowsSlicePtr, err, error_code.PARAM_ERR
	}
	cache.SetVigoInfoCache(funcKey, funcFac.RowsSlicePtr)
	return funcFac.RowsSlicePtr, nil, error_code.SUCCESS_STATUS
}

// 根据权限获取菜单
func GetNavigationByRoleIds(roleIds []int64) ([]databases.Tpo_Sys_Navigations, error) {
	naviFac := databases.NewNavigationFactory()
	err := naviFac.FindInfoByRoles(roleIds)
	return naviFac.RowsSlicePtr, err
}

// 获取用户的权限 @cache db
func GetRoles(userId int64) (param_type.ApiRoleInfoResponse, error, error_code.Code_type_int) {
	var data param_type.ApiRoleInfoResponse
	cache := NewVigoCache()
	defer cache.Close()
	roleKey := strconv.FormatInt(userId, 10) + VIGO_ROLES
	val := cache.GetVigoInfoCache(roleKey)
	if val != nil {
		json.Unmarshal(val.([]byte), &data)
		return data, nil, error_code.SUCCESS_STATUS
	}
	// 读数据写缓存
	roleIds, err, status := GetRoleIds(userId)
	if err != nil {
		return data, err, status
	}
	// 此用户没有权限
	if len(roleIds) == 0 {
		return data, nil, error_code.SUCCESS_STATUS
	}
	roleFac := databases.NewRolesFactory()
	err = roleFac.FindInfoByRoleIds(roleIds...)
	if err != nil {
		return data, err, error_code.DB_ERR
	}
	data.Data = roleFac.RowsSlicePtr
	cache.SetVigoInfoCache(roleKey, data)
	return data, nil, error_code.SUCCESS_STATUS
}

// 根据用户id获取所有权限 id
func GetRoleIds(userId int64) ([]int64, error, error_code.Code_type_int) {
	userRoleFac := databases.NewUserRolesFactory()
	err := userRoleFac.FindInfoByUserId(userId)
	roleIds := []int64{}
	if err != nil {
		return roleIds, err, error_code.PARAM_ERR
	}
	for _, val := range userRoleFac.RowsSlicePtr {
		roleIds = append(roleIds, val.RoleId)
	}

	return roleIds, nil, error_code.SUCCESS_STATUS
}

// 获取用户的菜单列表
func GetNavigationUser(appId int32, userId int64) ([]databases.Tpo_Sys_Navigations, error) {
	naviFac := databases.NewNavigationFactory()
	naviFac.FindInfoUser(appId, userId)
	var data []databases.Tpo_Sys_Navigations
	for _, val := range naviFac.UserNaviPtr {
		data = append(data, val.Tpo_Sys_Navigations)
	}
	return data, nil
}

// 获取菜单列表 @cache db
func GetNavigationByAppId(appId int32) ([]databases.Tpo_Sys_Navigations, error) {
	var data []databases.Tpo_Sys_Navigations
	cache := NewVigoCache()
	defer cache.Close()
	navKey := strconv.Itoa(int(appId)) + VIGO_NAVIGATION
	val := cache.GetVigoInfoCache(navKey)
	if val != nil {
		json.Unmarshal(val.([]byte), &data)
		return data, nil
	}

	naviFac := databases.NewNavigationFactory()
	err := naviFac.FindInfoByAppId(appId)
	if err != nil {
		return naviFac.RowsSlicePtr, err
	}
	cache.SetVigoInfoCache(navKey, naviFac.RowsSlicePtr)
	return naviFac.RowsSlicePtr, err
}

// 获取 app 菜单树
func GetAppNavigation(appId int32) ([]param_type.ApiTpoSysNavigation, error) {
	var data []param_type.ApiTpoSysNavigation
	// read cache
	navAppTreeKey := strconv.Itoa(int(appId)) + VIGO_NAVIGATION_NODE
	cache := NewVigoCache()
	defer cache.Close()
	val := cache.GetVigoInfoCache(navAppTreeKey)
	if val != nil {
		err := json.Unmarshal(val.([]byte), &data)
		if err == nil {
			return data, nil
		}
	}
	// 查询数据库
	navFac := databases.NewNavigationFactory()
	err := navFac.FindInfoByAppId(appId)
	if err != nil {
		return data, err
	}
	var treeNavi param_type.ApiTpoSysNavigation
	treeNavi.NavigationId = 0
	GetNavigationChildNode(&treeNavi, navFac.RowsSlicePtr)
	// set cache
	cache.SetVigoInfoCache(navAppTreeKey, treeNavi.ChildNavigations)
	return treeNavi.ChildNavigations, nil
}

// 获取用户菜单树 @cache api
func GetNavigationTree(appId int32, userId int64) ([]param_type.ApiTpoSysNavigation, error) {
	var data []param_type.ApiTpoSysNavigation
	// res, err := GetNavigationByAppId(appId)
	navTreeKey := strconv.Itoa(int(appId)) + "_" + strconv.FormatInt(userId, 10) + VIGO_NAVIGATION_NODE
	cache := NewVigoCache()
	defer cache.Close()
	val := cache.GetVigoInfoCache(navTreeKey)
	if val != nil {
		json.Unmarshal(val.([]byte), &data)
		return data, nil
	}
	// 读数据 写缓存
	roleIds, _, _ := GetRoleIds(userId)
	roleNav, _ := GetNavigationByRoleIds(roleIds)
	resT, err := GetNavigationUser(appId, userId)
	res := MergeNavigation(&resT, &roleNav, appId)
	var treeNavi param_type.ApiTpoSysNavigation
	treeNavi.NavigationId = 0
	if err != nil {
		return treeNavi.ChildNavigations, err
	}
	GetNavigationChildNode(&treeNavi, res)

	cache.SetVigoInfoCache(navTreeKey, treeNavi.ChildNavigations)
	return treeNavi.ChildNavigations, nil
}

// 菜单去重、合并、排序
func MergeNavigation(navigation1, navigation2 *[]databases.Tpo_Sys_Navigations, appId int32) []databases.Tpo_Sys_Navigations {
	for _, nav2 := range *navigation2 {
		if nav2.AppId == int64(appId) {
			*navigation1 = append(*navigation1, nav2)
		}
	}
	nav := RmDumpNavigation(navigation1)
	return SortNoNavigation(nav)
}

// 按 SortNo 排序
func SortNoNavigation(list []databases.Tpo_Sys_Navigations) []databases.Tpo_Sys_Navigations {
	count := len(list)
	for i := 0; i < count; i++ {
		for j := 0; j < count; j++ {
			if list[i].SortNo < list[j].SortNo {
				tmp := list[i]
				list[i] = list[j]
				list[j] = tmp
			}
		}
	}
	return list
}

// 菜单去重
func RmDumpNavigation(list *[]databases.Tpo_Sys_Navigations) []databases.Tpo_Sys_Navigations {
	var nav []databases.Tpo_Sys_Navigations
	for _, i := range *list {
		if len(nav) == 0 {
			nav = append(nav, i)
		} else {
			for k, v := range nav {
				if v.NavigationId == i.NavigationId {
					break
				}
				if k == len(nav)-1 {
					nav = append(nav, i)
				}
			}
		}
	}

	return nav
}

// 处理节点
func GetNavigationChildNode(treeNavi *param_type.ApiTpoSysNavigation, naviList []databases.Tpo_Sys_Navigations) {
	var tmpNav param_type.ApiTpoSysNavigation
	var tmpNavList []param_type.ApiTpoSysNavigation
	for _, naviVal := range naviList {
		if naviVal.ParentID == treeNavi.NavigationId {
			tmpNav.Tpo_Sys_Navigations = naviVal
			GetNavigationChildNode(&tmpNav, naviList)
			tmpNavList = append(tmpNavList, tmpNav)
		}
	}
	treeNavi.ChildNavigations = tmpNavList
}

// 全部部门树
func GetAllDepartTree() ([]param_type.ApiTpoSysDepart, error) {
	var departListTmp []param_type.ApiTpoSysDepart

	vigoCache := NewVigoCache()
	defer vigoCache.Close()
	// 读缓存
	departKeyStr := VIGO_DEPARTMENT_ALL
	depVal := vigoCache.GetVigoInfoCache(departKeyStr)
	if depVal != nil {
		err := json.Unmarshal(depVal.([]byte), &departListTmp)
		return departListTmp, err
	}

	departFac := databases.NewDepartFactory()
	departFac.FindInfoByParentId(0)
	if len(departFac.RowsSlicePtr) == 0 {
		return departListTmp, nil
	}
	departId := departFac.RowsSlicePtr[0].DeparentId

	departDataParentMap, _ := GetAllDepart()

	departFac.FindInfoByDepartIds(departId)
	departData := departFac.RowsSlicePtr
	// 所有用户部门关系
	userDepartData := GetUserDepartAll()
	var tmpDepart param_type.ApiTpoSysDepart
	for _, val := range departData {
		tmpDepart.Tpo_Sys_Departments = val
		tmpDepart.UserList, _ = userDepartData[val.DeparentId]
		GetDepartTree(&tmpDepart, departDataParentMap, userDepartData)
		departListTmp = append(departListTmp, tmpDepart)
	}
	// 写缓存
	vigoCache.SetVigoInfoCache(departKeyStr, departListTmp)
	return departListTmp, nil
}

// 根据部门 ID 获取自己的子节点
func GetDepartNodeByDepartIdIT(departId int64, departList []param_type.ApiTpoSysDepart, result *param_type.ApiTpoSysDepart) {
	for _, val := range departList {
		if val.DeparentId == departId {
			*result = val
			return
		} else {
			GetDepartNodeByDepartIdIT(departId, val.ChildDepartments, result)
		}
	}
	return
}

// 获取部门子节点，根据部门 ID api @cache
func GetDepartNodeByDepartId(departId int64) ([]param_type.ApiTpoSysDepart, error) {
	var departListTmp []param_type.ApiTpoSysDepart
	var result param_type.ApiTpoSysDepart
	//vigoCache := NewVigoCache()
	//defer vigoCache.Close()
	// 读缓存
	//departKeyStr := strconv.FormatInt(departId, 10) + VIGO_DEPARTMENT
	//depVal := vigoCache.GetVigoInfoCache(departKeyStr)
	//if depVal != nil {
	//	err := json.Unmarshal(depVal.([]byte), &departListTmp)
	//	return departListTmp, err
	//}
	departList, err := GetAllDepartTree()
	GetDepartNodeByDepartIdIT(departId, departList, &result)
	departListTmp = append(departListTmp, result)

	// 写缓存
	//vigoCache.SetVigoInfoCache(departKeyStr, departListTmp)
	return departListTmp, err
}

func GetDepartNode(userId int64) (param_type.ApiDepartmentVirtualResult, error) {
	var departListTmp, departVirtual []param_type.ApiTpoSysDepart
	var response param_type.ApiDepartmentVirtualResult
	vigoCache := NewVigoCache()
	defer vigoCache.Close()
	departKeyStr := strconv.FormatInt(userId, 10) + VIGO_DEPARTMENT_U
	depVal := vigoCache.GetVigoInfoCache(departKeyStr)
	if depVal != nil {
		err := json.Unmarshal(depVal.([]byte), &response)
		if err == nil {
			return response, nil
		} else {
			vigo_loger.AddGrayLog(err.Error())
		}
	}

	departIds, virtualIds, _ := GetDepartIdsByUserId(userId)

	departListAll, err := GetAllDepartTree()

	if len(departIds) > 0 {
		for _, val := range departIds {
			var resultDepart param_type.ApiTpoSysDepart
			GetDepartNodeByDepartIdIT(val, departListAll, &resultDepart)
			departListTmp = append(departListTmp, resultDepart)
		}
	}
	if len(virtualIds) > 0 {
		for _, val := range virtualIds {
			var resultDepartVirtual param_type.ApiTpoSysDepart
			GetDepartNodeByDepartIdIT(val, departListAll, &resultDepartVirtual)
			departVirtual = append(departVirtual, resultDepartVirtual)
		}
	}
	response.Tpo_Sys_Departments = departListTmp
	response.Tpo_Sys_Departments_Virtual = departVirtual
	vigoCache.SetVigoInfoCache(departKeyStr, response)
	return response, err
}

// GetAllDepartTreeAllUserInfo

func GetDepartNodeAllUser(userId int64) (param_type.ApiDepartmentVirtualResult, error) {
	var departListTmp, departVirtual []param_type.ApiTpoSysDepart
	var response param_type.ApiDepartmentVirtualResult
	vigoCache := NewVigoCache()
	defer vigoCache.Close()
	departKeyStr := strconv.FormatInt(userId, 10) + VIGO_DEPARTMENT_U_ALL
	depVal := vigoCache.GetVigoInfoCache(departKeyStr)
	if depVal != nil {
		err := json.Unmarshal(depVal.([]byte), &response)
		if err == nil {
			return response, nil
		} else {
			vigo_loger.AddGrayLog(err.Error())
		}
	}

	departIds, virtualIds, _ := GetDepartIdsByUserId(userId)

	departListAll, err := GetAllDepartTreeAllUserInfo()
	if len(departIds) > 0 {
		for _, val := range departIds {
			var resultDepart param_type.ApiTpoSysDepart
			GetDepartNodeByDepartIdIT(val, departListAll, &resultDepart)
			departListTmp = append(departListTmp, resultDepart)
		}
	}
	if len(virtualIds) > 0 {
		for _, val := range virtualIds {
			var resultDepartVirtual param_type.ApiTpoSysDepart
			GetDepartNodeByDepartIdIT(val, departListAll, &resultDepartVirtual)
			departVirtual = append(departVirtual, resultDepartVirtual)
		}
	}
	response.Tpo_Sys_Departments = departListTmp
	response.Tpo_Sys_Departments_Virtual = departVirtual
	vigoCache.SetVigoInfoCache(departKeyStr, response)
	return response, err
}

// 获取部门节点 api @cache
func GetDepartNodeT(userId int64) ([]param_type.ApiTpoSysDepart, error) {
	var departListTmp []param_type.ApiTpoSysDepart
	vigoCache := NewVigoCache()
	defer vigoCache.Close()
	departKeyStr := strconv.FormatInt(userId, 10) + VIGO_DEPARTMENT_U
	depVal := vigoCache.GetVigoInfoCache(departKeyStr)
	if depVal != nil {
		err := json.Unmarshal(depVal.([]byte), &departListTmp)
		return departListTmp, err
	}
	// 根据用户获取所有部门 id
	departIds, _, err := GetDepartIdsByUserId(userId)
	if err != nil {
		return departListTmp, err
	}
	// 所有用户部门关系
	userDepartData := GetUserDepartAll()
	departDataParentMap, _ := GetAllDepart()

	departFac := databases.NewDepartFactory()
	departFac.FindInfoByDepartIds(departIds...)
	departData := departFac.RowsSlicePtr

	var tmpDepart param_type.ApiTpoSysDepart
	for _, val := range departData {
		tmpDepart.Tpo_Sys_Departments = val
		tmpDepart.UserList, _ = userDepartData[val.DeparentId]
		GetDepartTree(&tmpDepart, departDataParentMap, userDepartData)
		departListTmp = append(departListTmp, tmpDepart)
	}
	vigoCache.SetVigoInfoCache(departKeyStr, departListTmp)

	return departListTmp, nil
}

// 获取部门树
func GetDepartTree(departTree *param_type.ApiTpoSysDepart, departList map[int64]databases.Tpo_Sys_Departments, userDepartData map[int64][]databases.Tpo_Sys_Users) {

	var departData []databases.Tpo_Sys_Departments
	for _, departVal := range departList {
		if departVal.ParentId == departTree.DeparentId {
			departData = append(departData, departVal)
		}
	}
	if len(departData) == 0 {
		return
	}
	var departListTmp []param_type.ApiTpoSysDepart
	for _, val := range departData {
		tmpDepart := param_type.ApiTpoSysDepart{}
		tmpDepart.Tpo_Sys_Departments = val
		tmpDepart.UserList, _ = userDepartData[val.DeparentId]
		GetDepartTree(&tmpDepart, departList, userDepartData)
		departListTmp = append(departListTmp, tmpDepart)
	}
	departTree.ChildDepartments = departListTmp
}

// leader tree
func GetLeaderTree(userId int64) ([]param_type.LeaderData, error) {
	var leaderData []param_type.LeaderData
	vigoCache := NewVigoCache()
	defer vigoCache.Close()
	leaderKeyStr := strconv.FormatInt(userId, 10) + VIGO_DEPARTLEADER
	leadVal := vigoCache.GetVigoInfoCache(leaderKeyStr)
	if leadVal != nil {
		err := json.Unmarshal(leadVal.([]byte), &leaderData)
		return leaderData, err
	}
	// 所有部门
	departData, err := GetAllDepart()
	if err != nil {
		return leaderData, err
	}
	departUserFac := databases.NewDepartUserFactory()

	// 用户对应部门
	departUserFac.FindInfoByUserId(userId)
	// 所有用户
	usersList := GetUserAll()

	for _, val := range departUserFac.RowsSlicePtr {
		var tmpLeader param_type.LeaderData
		tmpLeader.DepartId = val.DeparentId
		GetParentNode(&tmpLeader, departData, usersList)
		leaderData = append(leaderData, tmpLeader)
	}
	err = vigoCache.SetVigoInfoCache(leaderKeyStr, leaderData)
	return leaderData, err
}

// 所有 部门 map  部门 id 为  key
func GetAllDepart() (map[int64]databases.Tpo_Sys_Departments, error) {
	data := make(map[int64]databases.Tpo_Sys_Departments)

	vigoCache := NewVigoCache()
	defer vigoCache.Close()
	// 读缓存
	departKeyStr := VIGO_DEPARTMENT_USER_MAP
	depVal := vigoCache.GetVigoInfoCache(departKeyStr)
	if depVal != nil {
		err := json.Unmarshal(depVal.([]byte), &data)
		return data, err
	}
	// 写缓存
	departFac := databases.NewDepartFactory()
	err := departFac.FindAllInfo()
	if err != nil {
		return data, err
	}
	p.Lock()
	for _, val := range departFac.RowsSlicePtr {
		data[val.DeparentId] = val
	}
	p.Unlock()
	vigoCache.SetVigoInfoCache(departKeyStr, data)
	return data, nil
}

// 所有 部门 map  部门 parent id 为  key
func GetAllDepartParent() (map[int64][]databases.Tpo_Sys_Departments, error) {
	data := make(map[int64][]databases.Tpo_Sys_Departments)
	departFac := databases.NewDepartFactory()
	err := departFac.FindAllInfo()
	if err != nil {
		return data, err
	}
	p.Lock()
	for _, val := range departFac.RowsSlicePtr {
		data[val.ParentId] = append(data[val.ParentId], val)
	}
	p.Unlock()
	return data, nil
}

// 获取部门父节点
func GetParentNode(leader *param_type.LeaderData, departLeaderList map[int64]databases.Tpo_Sys_Departments, userList map[int64]databases.Tpo_Sys_Users) {
	var ok bool
	_, ok = departLeaderList[leader.DepartId]
	if !ok {
		return
	}
	leader.DepartName = departLeaderList[leader.DepartId].Name
	leaders := strings.Split(departLeaderList[leader.DepartId].Leader_id, ",")
	if len(leaders) > 0 {
		for _, leaderIdStr := range leaders {
			leaderId, err := strconv.Atoi(leaderIdStr)
			if err != nil {
				//vigo_loger.AddGrayLog(gderror.New(err.Error()).Error())
				break
			}
			leader.LeaderName = append(leader.LeaderName, struct {
				UserId   int64
				UserName string
			}{UserId: int64(leaderId), UserName: userList[int64(leaderId)].UserName})
		}
	}
	parentId := departLeaderList[leader.DepartId].ParentId

	_, ok = departLeaderList[parentId]
	if !ok {
		return
	}

	var tmpData param_type.LeaderData
	tmpData.DepartId = departLeaderList[parentId].DeparentId

	leader.ParentLeader = &tmpData

	GetParentNode(leader.ParentLeader, departLeaderList, userList)
}

// 获取所有用户部门关系
func GetUserDepartAll() map[int64][]databases.Tpo_Sys_Users {
	userFac := databases.NewUserFactory()
	userFac.FindUserDepartAll(false)
	result := userFac.DepartUserPtr
	data := make(map[int64][]databases.Tpo_Sys_Users)
	p.Lock()
	for _, depUser := range result {
		data[depUser.DeparentId] = append(data[depUser.DeparentId], depUser.Tpo_Sys_Users)
	}
	p.Unlock()
	return data
}

// 获取所有用户部门关系 用户全信息
func GetUserDepartAllUserInfo() map[int64][]databases.Tpo_Sys_Users {
	userFac := databases.NewUserFactory()
	userFac.FindUserDepartAll(true)
	result := userFac.DepartUserPtr
	data := make(map[int64][]databases.Tpo_Sys_Users)
	p.Lock()
	for _, depUser := range result {
		data[depUser.DeparentId] = append(data[depUser.DeparentId], depUser.Tpo_Sys_Users)
	}
	p.Unlock()
	return data
}

// 全部部门树
func GetAllDepartTreeAllUserInfo() ([]param_type.ApiTpoSysDepart, error) {
	var departListTmp []param_type.ApiTpoSysDepart

	vigoCache := NewVigoCache()
	defer vigoCache.Close()
	// 读缓存
	departKeyStr := VIGO_DEPARTMENT_ALL_U
	depVal := vigoCache.GetVigoInfoCache(departKeyStr)
	if depVal != nil {
		err := json.Unmarshal(depVal.([]byte), &departListTmp)
		return departListTmp, err
	}

	departFac := databases.NewDepartFactory()
	departFac.FindInfoByParentId(0)
	if len(departFac.RowsSlicePtr) == 0 {
		return departListTmp, nil
	}
	departId := departFac.RowsSlicePtr[0].DeparentId

	departDataParentMap, _ := GetAllDepart()

	departFac.FindInfoByDepartIds(departId)
	departData := departFac.RowsSlicePtr
	// 所有用户部门关系
	userDepartData := GetUserDepartAllUserInfo()
	var tmpDepart param_type.ApiTpoSysDepart
	for _, val := range departData {
		tmpDepart.Tpo_Sys_Departments = val
		tmpDepart.UserList, _ = userDepartData[val.DeparentId]
		GetDepartTree(&tmpDepart, departDataParentMap, userDepartData)
		departListTmp = append(departListTmp, tmpDepart)
	}
	// 写缓存
	vigoCache.SetVigoInfoCache(departKeyStr, departListTmp)
	return departListTmp, nil
}

func FindDepartByFuncIDs(appId int32, funcKey string) ([]param_type.ApiTpoSysDepart, error) {
	funcFac := databases.NewFuncFactory()
	if err := funcFac.FindInfoByFuncKey(appId, funcKey); err != nil || len(funcFac.RowsSlicePtr) == 0 {
		return nil, errors.New("not find")
	}
	funcIds := []int64{}
	for _, v := range funcFac.RowsSlicePtr {
		funcIds = append(funcIds, v.FunctionId)
	}

	userFuc := databases.NewUserFuncFactory()
	err := userFuc.FindInfoByFuncIds(funcIds...)
	if err != nil {
		return nil, err
	}
	var userIds = []int64{}
	for _, val := range userFuc.RowsSlicePtr {
		userIds = append(userIds, val.UserId)
	}
	return FindUsersDepartTree(userIds)
}

// 用户部门树
func FindUsersDepartTree(userIds []int64) ([]param_type.ApiTpoSysDepart, error) {
	var departListTmp []param_type.ApiTpoSysDepart

	departFac := databases.NewDepartFactory()
	departFac.FindInfoByParentId(0)
	if len(departFac.RowsSlicePtr) == 0 {
		return departListTmp, nil
	}
	departId := departFac.RowsSlicePtr[0].DeparentId

	departDataParentMap, _ := GetAllDepart()

	departFac.FindInfoByDepartIds(departId)
	departData := departFac.RowsSlicePtr
	// 所有用户部门关系
	userDepartData := FindUserDepartByUIDs(userIds)
	var tmpDepart param_type.ApiTpoSysDepart
	for _, val := range departData {
		tmpDepart.Tpo_Sys_Departments = val
		tmpDepart.UserList, _ = userDepartData[val.DeparentId]
		GetDepartTree(&tmpDepart, departDataParentMap, userDepartData)
		departListTmp = append(departListTmp, tmpDepart)
	}
	return departListTmp, nil
}

// 获取用户部门关系
func FindUserDepartByUIDs(userIds []int64) map[int64][]databases.Tpo_Sys_Users {
	userFac := databases.NewUserFactory()
	userFac.FindUserDepartAll(false)
	result := userFac.DepartUserPtr
	data := make(map[int64][]databases.Tpo_Sys_Users)
	//var userEmpty = databases.Tpo_Sys_Users{}
	p.Lock()
	for _, depUser := range result {
		if ok := SearchUserIDs(depUser.UserID, &userIds); ok {
			data[depUser.DeparentId] = append(data[depUser.DeparentId], depUser.Tpo_Sys_Users)
			//} else {
			//	data[depUser.DeparentId] = append(data[depUser.DeparentId], userEmpty)
		}
	}
	p.Unlock()
	return data
}

func SearchUserIDs(userId int64, userIds *[]int64) bool {
	if len(*userIds) == 0 {
		return false
	}
	for k, v := range *userIds {
		if v == userId {
			*userIds = append((*userIds)[:k], (*userIds)[k+1:]...)
			return true
		}
	}
	return false
}

// 获取所有用户
func GetUserAll() map[int64]databases.Tpo_Sys_Users {
	userData := make(map[int64]databases.Tpo_Sys_Users)
	users, err := GetUserByDB()
	if err != nil {
		vigo_loger.AddGrayLog(gderror.New(err.Error()).Error())
	}
	p.Lock()
	for _, val := range users {
		userData[val.UserID] = val
	}
	p.Unlock()
	return userData
}

// all user for table
func GetUserByDB() ([]databases.Tpo_Sys_Users, error) {
	var userData []databases.Tpo_Sys_Users
	keyStr := VIGO_USERS_ALL
	vigoCache := NewVigoCache()
	defer vigoCache.Close()
	val := vigoCache.GetVigoInfoCache(keyStr)
	if val == nil {
		userFac := databases.NewUserFactory()
		err := userFac.FindAll()
		userData = userFac.RowsSlicePtr
		vigoCache.SetVigoInfoCache(keyStr, userData)
		return userData, err
	}
	err := json.Unmarshal(val.([]byte), &userData)
	return userData, err

}

// 根据角色获取部门用户
func GetDepartUserByRole(roleId int64) (param_type.ApiDepartmentRoleResponse, error, error_code.Code_type_int) {
	var apiResponse param_type.ApiDepartmentRoleResponse
	var partData param_type.ApiTpoSysDepart
	keyStr := strconv.FormatInt(roleId, 10) + VIGO_ROLE_DEPART
	vigoCache := NewVigoCache()
	defer vigoCache.Close()
	val := vigoCache.GetVigoInfoCache(keyStr)
	if val != nil {
		err := json.Unmarshal(val.([]byte), &apiResponse)
		if err != nil {
			vigo_loger.AddGrayLog(gderror.New(err.Error()).Error())
		}
		return apiResponse, err, error_code.PARAM_ERR
	}

	departFac := databases.NewDepartFactory()
	departFac.FindInfoByParentId(0)

	data, err := GetDepartNodeByDepartId(departFac.RowsSlicePtr[0].DeparentId)
	if err != nil {
		return apiResponse, err, error_code.PARAM_ERR
	}

	roleUserData, err := GetRoleUsers(roleId)
	if err != nil {
		return apiResponse, err, error_code.PARAM_ERR
	}

	userData, err := GetUserByRoleUser(roleUserData)
	if err != nil {
		return apiResponse, err, error_code.PARAM_ERR
	}

	GetDepartUser(&partData, data, roleUserData)
	if len(partData.ChildDepartments) == 0 {
		return apiResponse, errors.New("not find role"), error_code.NOT_FIND_ERR
	}
	apiResponse.RoleDepartUser = partData.ChildDepartments[0]
	apiResponse.TpoSysUsers = userData
	// 设置缓存
	vigoCache.SetVigoInfoCache(keyStr, apiResponse)
	return apiResponse, nil, error_code.SUCCESS_STATUS
}

func GetUserByRoleUser(roleUser map[int64]databases.Tpo_Sys_User_Roles) ([]databases.Tpo_Sys_Users, error) {
	var userIds []int64
	for _, val := range roleUser {
		userIds = append(userIds, val.UserId)
	}
	return GetUserByIds(userIds...)
}

// 部门用户过滤
func GetDepartUser(partData *param_type.ApiTpoSysDepart, data []param_type.ApiTpoSysDepart, roleUserData map[int64]databases.Tpo_Sys_User_Roles) {
	if len(roleUserData) == 0 || len(data) == 0 {
		return
	}
	var tmpPartData []param_type.ApiTpoSysDepart
	for _, val := range data {
		var tmpDepart param_type.ApiTpoSysDepart
		var tmpUser []databases.Tpo_Sys_Users
		tmpDepart.Tpo_Sys_Departments = val.Tpo_Sys_Departments
		tmpDepart.UserList = []databases.Tpo_Sys_Users{}
		tmpDepart.ChildDepartments = []param_type.ApiTpoSysDepart{}
		for _, userVal := range val.UserList {
			_, ok := roleUserData[userVal.UserID]
			if ok {
				//tmpDepart.ChildDepartments = val.ChildDepartments
				tmpUser = append(tmpUser, userVal)
				tmpDepart.UserList = tmpUser
				delete(roleUserData, userVal.UserID)
			}
		}
		GetDepartUser(&tmpDepart, val.ChildDepartments, roleUserData)
		if len(tmpDepart.UserList) == 0 && len(tmpDepart.ChildDepartments) == 0 {
			continue
		}
		tmpPartData = append(tmpPartData, tmpDepart)
	}
	partData.ChildDepartments = tmpPartData

}

// 获取角色所有用户 ids
func GetRoleUsers(roleId int64) (map[int64]databases.Tpo_Sys_User_Roles, error) {
	data := make(map[int64]databases.Tpo_Sys_User_Roles)
	roleUserFac := databases.NewUserRolesFactory()
	err := roleUserFac.FindInfoByRoleId(roleId)
	if err != nil {
		return data, err
	}
	p.Lock()
	for _, val := range roleUserFac.RowsSlicePtr {
		data[val.UserId] = val
	}
	p.Unlock()
	return data, nil
}

// 根据用户 id list 获取用户
func GetUserInfoByIds(userData map[int64]databases.Tpo_Sys_Users, userIds ...int64) ([]databases.Tpo_Sys_Users, error) {
	var valData []databases.Tpo_Sys_Users
	for _, userId := range userIds {
		for _, uVal := range userData {
			if uVal.UserID == userId {
				valData = append(valData, uVal)
			}
		}
	}

	return valData, nil
}

// department id 获取用户 ids
func GetUserIdsByDepartId(departId int64) ([]int64, error) {
	var userIds []int64
	depUsrFac := databases.NewDepartUserFactory()
	err := depUsrFac.FindInfoByDepartId(departId)
	if err != nil {
		return userIds, err
	}
	for _, val := range depUsrFac.RowsSlicePtr {
		userIds = append(userIds, val.UserId)
	}

	return userIds, nil
}

// user id 获取部门 ids
func GetDepartIdsByUserId(userId int64) ([]int64, []int64, error) {
	var departIds, virtualIds []int64
	depUsrFac := databases.NewDepartUserFactory()
	err := depUsrFac.FindInfoByUserId(userId)
	if err != nil {
		return departIds, virtualIds, err
	}
	for _, val := range depUsrFac.RowsSlicePtr {
		if val.DepartRelation == 0 {
			departIds = append(departIds, val.DeparentId)
		} else {
			virtualIds = append(virtualIds, val.DeparentId)
		}
	}
	return departIds, virtualIds, nil
}

// GetUserInfoByErp 用户信息
func GetUserInfoByErp(erpId ...string) ([]databases.Tpo_Sys_Users, error) {
	userFac := databases.NewUserFactory()
	err := userFac.FindUserInfoErp(erpId...)
	return userFac.RowsSlicePtr, err
}

func GetUserRoleByIds(userIds ...int64) ([]databases.Tpo_Sys_User_Roles, error) {
	userRoleFac := databases.NewUserRolesFactory()
	err := userRoleFac.FindInfoByUserIds(userIds...)
	return userRoleFac.RowsSlicePtr, err
}

func GetUserByIds(userId ...int64) ([]databases.Tpo_Sys_Users, error) {
	userFac := databases.NewUserFactory()
	err := userFac.FindUserInfoIds(userId...)
	return userFac.RowsSlicePtr, err
}

// 根据坐席号获取用户
func GetUserByAgents(AgentNu ...string) ([]databases.Tpo_Sys_Users, error) {
	var userData []databases.Tpo_Sys_Users
	users := GetUserAll()
	for _, agent := range AgentNu {
		for _, user := range users {
			if user.AgentNO == agent && agent != "" {
				userData = append(userData, user)
			}
		}
	}
	if len(userData) == 0 {
		return userData, errors.New("not find")
	}

	return userData, nil
}

// 根据工号获取用户
func GetUserByWorkIds(workIds ...string) ([]databases.Tpo_Sys_Users, error) {
	var userData []databases.Tpo_Sys_Users
	users := GetUserAll()
	for _, agent := range workIds {
		for _, user := range users {
			if user.WorkNo == agent && agent != "" {
				userData = append(userData, user)
			}
		}
	}
	if len(userData) == 0 {
		return userData, errors.New("not find")
	}

	return userData, nil
}

func GetUserByMobiles(mobiles ...string) ([]databases.Tpo_Sys_Users, error) {
	userFac := databases.NewUserFactory()
	err := userFac.GetUserInfoByPhones(mobiles...)
	return userFac.RowsSlicePtr, err
}

// 根据分机号获取用户信息
func GetUserByPartial(partials ...string) ([]databases.Tpo_Sys_Users, error) {
	var userData []databases.Tpo_Sys_Users
	userFac := databases.NewUserFactory()
	userFac.FindUserInfoByPartialPhone(partials...)

	if len(userFac.RowsSlicePtr) == 0 {
		return userData, errors.New("not find")
	}

	return userFac.RowsSlicePtr, nil
}

// 根据天润坐席号获取用户信息
func GetUserByTrAgentNo(trAgentNos ...string) ([]databases.Tpo_Sys_Users, error) {
	var userData []databases.Tpo_Sys_Users
	userFac := databases.NewUserFactory()
	userFac.FindUserInfoByTrAgentNo(trAgentNos...)

	if len(userFac.RowsSlicePtr) == 0 {
		return userData, errors.New("not find")
	}

	return userFac.RowsSlicePtr, nil
}

// IsValidUserInfo 是否是有效的用户信息
// 目前主要判断用户座机号
func IsValidUserInfo(userId int64, data *databases.Tpo_Sys_Users) (bool, error) {
	userFac := databases.NewUserFactory()
	has, err := userFac.GetUserInfoByPartialPhone(data.PartialPhone)
	if err != nil {
		return false, err
	}

	if !has {
		return true, nil
	}

	if userFac.Table.UserID == userId {
		return true, nil
	}

	return false, nil
}

// 根据用户ID修改信息 (daili)
func EditUserByUserId(userId int64, data *databases.Tpo_Sys_Users) error {
	userFac := databases.NewUserFactory()
	userFac.Table = *data
	return userFac.EditUserDaili(userId)
}

func FindUserAliMQ(userId []int64) ([]databases.Tpo_Sys_User_AliyunMq, error) {
	userAliFac := databases.NewUserAliMQ()
	err := userAliFac.FindInfoByUserId(userId...)
	return userAliFac.RowsSlicePtr, err
}

// 获取所有的角色
func FindRoles() ([]databases.Tpo_Sys_Roles, error) {
	roleF := databases.NewRolesFactory()
	err := roleF.FindAllInfo()
	return roleF.RowsSlicePtr, err
}

func FindPermission(userId int64) (interface{}, error, error_code.Code_type_int) {
	roles, err, errCode := GetRoles(userId) // role
	if err != nil {
		return nil, err, errCode
	}
	users, err := GetUserByIds(userId) // user
	if err != nil {
		return nil, err, error_code.DB_ERR
	}
	duf := databases.NewDepartUserFactory()
	duf.FindInfoByUserId(userId)
	departIds := []int64{}
	for _, val := range duf.RowsSlicePtr {
		departIds = append(departIds, val.DeparentId)
	}
	df := databases.NewDepartFactory()
	df.FindInfoByDepartIds(departIds...)

	return struct {
		Tpo_Users      interface{}
		Tpo_Roles      interface{}
		Tpo_Deparments interface{}
	}{Tpo_Users: users, Tpo_Roles: roles.Data, Tpo_Deparments: df.RowsSlicePtr}, nil, error_code.SUCCESS_STATUS
}
func FindDepartByCampus(campusId, campusType int32) ([]int64, error) {
	df := databases.NewDepartFactory()
	var err error
	var data = []int64{}
	if err = df.FindByCampus(campusId, campusType); err == nil {
		for _, val := range df.RowsSlicePtr {
			data = append(data, val.DeparentId)
		}
	}
	return data, err
}

// 修改用户密码
func ResetPassword(account, password string) (error, error_code.Code_type_int) {
	if ok := vigo_tool.VerifyPwd(password); !ok {
		return errors.New("password format fail"), error_code.PASSWORD_FORMAT_ERR
	}
	accType, err := vigo_tool.IsPhoneOrEmail(account)
	userFac := databases.NewUserFactory()
	if err != nil {
		return err, error_code.PHONE_EMAIL_NOT_EXISTS_ERR
	}
	if accType == vigo_tool.EMAIL {
		userFac.GetUserInfoByEmail(account)
	} else if accType == vigo_tool.PHONE {
		userFac.GetUserInfoByPhone(account)
	}
	password = vigo_tool.GetPassword(password, "")
	return userFac.EditPwd(userFac.Table.UserID, password[0:20]), error_code.DB_ERR
}

// 添加 eds 用户 临时 （todo delete）
func EdsAddUser(users *databases.Tpo_Sys_Users, ErpDepartId string) (error, error_code.Code_type_int) {
	userFac := databases.NewUserFactory()
	//if ok, _ := userFac.ExistErpUerId(users.ErpUserId); ok {
	//	return errors.New("erp user id is exist"), error_code.REDIS_ERR
	//}
	userFac.Table = *users
	userFac.Table.Birthday = "2017-01-01 00:00:00"
	_, err := userFac.Add()
	if err != nil {
		return err, error_code.DB_ERR
	}

	// 根据 erp id 查询部门 ID
	departFac := databases.NewDepartFactory()
	//if err := departFac.FindByErpId(users.ErpDepartmentId); err != nil {
	//	return err, error_code.DB_ERR
	//}

	departId := departFac.Table.DeparentId
	if departFac.Table.DeparentId == 0 {
		departId = 913 // 如果为 0， eds 要求写死
	}

	// 加入关联
	departUserFac := databases.NewDepartUserFactory()
	departUserFac.Table.UserId = userFac.Table.UserID
	departUserFac.Table.DeparentId = departId
	if _, err := departUserFac.EdsAddRelation(); err != nil {
		return err, error_code.DB_ERR
	}

	return nil, error_code.SUCCESS_STATUS
}

// 根据条件获取用户信息
func GetUserByCondition(userId string, mainroleInt string, TrueNameStr string, deparentIdInt string, offsetInt string, limitInt string) map[int64][]databases.Tpo_Sys_Users_Depart {
	userFac := databases.NewUserFactory()
	userFac.GetUserByCondition(userId, mainroleInt, TrueNameStr, deparentIdInt, offsetInt, limitInt)
	result := userFac.DepartUserPtr
	data := make(map[int64][]databases.Tpo_Sys_Users_Depart)
	var userDepart databases.Tpo_Sys_Users_Depart
	i := int64(0)
	p.Lock()
	for _, depUser := range result {
		// depUser.Tpo_Sys_Users.DeparentName = depUser.DeparentName
		// depUser.Tpo_Sys_Users.DeparentId   = int32(depUser.DeparentId)
		userDepart.UserID 		= depUser.Tpo_Sys_Users.UserID
		userDepart.Ename 		= depUser.Tpo_Sys_Users.Ename
		userDepart.WorkNo 		= depUser.Tpo_Sys_Users.WorkNo
		userDepart.UserName 	= depUser.Tpo_Sys_Users.UserName
		userDepart.Mobile 		= depUser.Tpo_Sys_Users.Mobile
		userDepart.Email 		= depUser.Tpo_Sys_Users.Email
		userDepart.TrueName 	= depUser.Tpo_Sys_Users.TrueName
		userDepart.Qq 			= depUser.Tpo_Sys_Users.Qq
		userDepart.Birthday 	= depUser.Tpo_Sys_Users.Birthday
		userDepart.CreateId 	= depUser.Tpo_Sys_Users.CreateId
		userDepart.CreateTime 	= depUser.Tpo_Sys_Users.CreateTime
		userDepart.CourseTypes 	= depUser.Tpo_Sys_Users.CourseTypes
		userDepart.IsPublic 	= depUser.Tpo_Sys_Users.IsPublic
		userDepart.OfficeAddr 	= depUser.Tpo_Sys_Users.OfficeAddr
		userDepart.Remark 		= depUser.Tpo_Sys_Users.Remark
		userDepart.Mainrole 	= depUser.Tpo_Sys_Users.Mainrole
		userDepart.DeparentName = depUser.DeparentName
		userDepart.DeparentId 	= int32(depUser.DeparentId)
		data[i] = append(data[depUser.Tpo_Sys_Users.UserID], userDepart)
		i++
	}
	p.Unlock()
	return data
}
